﻿using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Data;
using System.Text;
using XXF.Extensions;
using XXF.Db;
using Dyd.BaseService.ServiceCenter.Domain.Model;

namespace Dyd.BaseService.ServiceCenter.Domain.Dal
{
    //tb_node
    public partial class tb_node_dal
    {
        #region C

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(DbConn conn, tb_node model)
        {
            List<ProcedureParameter> par = new List<ProcedureParameter>();
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into tb_node(");
            strSql.Append("serviceid,sessionid,ip,port,runstate,nodeheartbeattime,boostpercent,errorcount,connectioncount,processthreadcount,processcpuper,memorysize,filesize,createtime,interfaceversion,protocoljson");
            strSql.Append(") values (");
            strSql.Append("@serviceid,@sessionid,@ip,@port,@runstate,@nodeheartbeattime,@boostpercent,@errorcount,@connectioncount,@processthreadcount,@processcpuper,@memorysize,@filesize,@createtime,@interfaceversion,@protocoljson");
            strSql.Append(") ");
            strSql.Append(";select @@IDENTITY");
            par.Add(new ProcedureParameter("@serviceid", model.serviceid));
            par.Add(new ProcedureParameter("@sessionid", model.sessionid));
            par.Add(new ProcedureParameter("@ip", model.ip));
            par.Add(new ProcedureParameter("@port", model.port));
            par.Add(new ProcedureParameter("@runstate", model.runstate));
            par.Add(new ProcedureParameter("@nodeheartbeattime", model.nodeheartbeattime));
            par.Add(new ProcedureParameter("@boostpercent", model.boostpercent));
            par.Add(new ProcedureParameter("@errorcount", model.errorcount));
            par.Add(new ProcedureParameter("@connectioncount", model.connectioncount));
            par.Add(new ProcedureParameter("@processthreadcount", model.processthreadcount));
            par.Add(new ProcedureParameter("@processcpuper", model.processcpuper));
            par.Add(new ProcedureParameter("@memorysize", model.memorysize));
            par.Add(new ProcedureParameter("@filesize", model.filesize));
            par.Add(new ProcedureParameter("@createtime", model.createtime));
            par.Add(new ProcedureParameter("@interfaceversion", model.interfaceversion));
            par.Add(new ProcedureParameter("@protocoljson", model.protocoljson));


            object obj = conn.ExecuteScalar(strSql.ToString(), par);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }

        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(DbConn conn, tb_node model)
        {
            List<ProcedureParameter> par = new List<ProcedureParameter>();
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update tb_node set ");

            strSql.Append(" serviceid = @serviceid , ");
            strSql.Append(" sessionid = @sessionid , ");
            strSql.Append(" ip = @ip , ");
            strSql.Append(" port = @port , ");
            strSql.Append(" runstate = @runstate , ");
            strSql.Append(" nodeheartbeattime = @nodeheartbeattime , ");
            strSql.Append(" boostpercent = @boostpercent , ");
            strSql.Append(" errorcount = @errorcount , ");
            strSql.Append(" connectioncount = @connectioncount , ");
            strSql.Append(" processthreadcount = @processthreadcount , ");
            strSql.Append(" processcpuper = @processcpuper , ");
            strSql.Append(" memorysize = @memorysize , ");
            strSql.Append(" filesize = @filesize , ");
            strSql.Append(" createtime = @createtime , ");
            strSql.Append(" interfaceversion = @interfaceversion , ");
            strSql.Append(" protocoljson = @protocoljson  ");
            strSql.Append(" where id=@id ");

            par.Add(new ProcedureParameter("@id", model.id));
            par.Add(new ProcedureParameter("@serviceid", model.serviceid));
            par.Add(new ProcedureParameter("@sessionid", model.sessionid));
            par.Add(new ProcedureParameter("@ip", model.ip));
            par.Add(new ProcedureParameter("@port", model.port));
            par.Add(new ProcedureParameter("@runstate", model.runstate));
            par.Add(new ProcedureParameter("@nodeheartbeattime", model.nodeheartbeattime));
            par.Add(new ProcedureParameter("@boostpercent", model.boostpercent));
            par.Add(new ProcedureParameter("@errorcount", model.errorcount));
            par.Add(new ProcedureParameter("@connectioncount", model.connectioncount));
            par.Add(new ProcedureParameter("@processthreadcount", model.processthreadcount));
            par.Add(new ProcedureParameter("@processcpuper", model.processcpuper));
            par.Add(new ProcedureParameter("@memorysize", model.memorysize));
            par.Add(new ProcedureParameter("@filesize", model.filesize));
            par.Add(new ProcedureParameter("@createtime", model.createtime));
            par.Add(new ProcedureParameter("@interfaceversion", model.interfaceversion));
            par.Add(new ProcedureParameter("@protocoljson", model.protocoljson));

            int rows = conn.ExecuteSql(strSql.ToString(), par);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(DbConn conn, int id)
        {
            List<ProcedureParameter> par = new List<ProcedureParameter>();
            par.Add(new ProcedureParameter("@id", id));
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from tb_node ");
            strSql.Append(" where id=@id");
            int rows = conn.ExecuteSql(strSql.ToString(), par);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 更新节点权重值
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="id">Id</param>
        /// <param name="boostPercent">权重值</param>
        /// <returns></returns>
        public bool UpdateNodeBoostPercent(DbConn conn, int id, int boostPercent)
        {
            List<ProcedureParameter> par = new List<ProcedureParameter>();
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update tb_node set ");
            strSql.Append(" boostpercent = @boostpercent ");
            strSql.Append(" where id=@id ");

            par.Add(new ProcedureParameter("@id", id));
            par.Add(new ProcedureParameter("@boostpercent", boostPercent));
            int rows = conn.ExecuteSql(strSql.ToString(), par);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region Q
        /// <summary>
        /// 重复规则
        /// </summary>
        public bool IsExists(DbConn conn, tb_node model)
        {
            List<ProcedureParameter> par = new List<ProcedureParameter>();
            StringBuilder stringSql = new StringBuilder();
            stringSql.Append(@"select top 1 id from tb_category with (nolock) s where 1=1");
            DataSet ds = new DataSet();
            conn.SqlToDataSet(ds, stringSql.ToString(), par);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public tb_node Get(DbConn conn, int id)
        {
            List<ProcedureParameter> par = new List<ProcedureParameter>();
            par.Add(new ProcedureParameter("@id", id));
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select id, serviceid, sessionid, ip, port, runstate, nodeheartbeattime, boostpercent, errorcount, connectioncount, processthreadcount, processcpuper, memorysize, filesize, createtime, interfaceversion, protocoljson  ");
            strSql.Append(" from tb_node with (nolock) ");
            strSql.Append(" where id=@id");
            DataSet ds = new DataSet();
            conn.SqlToDataSet(ds, strSql.ToString(), par);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                return CreateModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public IList<tb_node> GetTimeOutNode(DbConn conn, int timeOutSenconds)
        {
            List<tb_node> list = new List<tb_node>();
            List<ProcedureParameter> par = new List<ProcedureParameter>();
            par.Add(new ProcedureParameter("@timeOutSenconds", timeOutSenconds));
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select id, serviceid, sessionid, ip, port, runstate, nodeheartbeattime, boostpercent, errorcount, connectioncount, processthreadcount, processcpuper, memorysize, filesize, createtime, interfaceversion, protocoljson  ");
            strSql.Append(" from tb_node with (nolock) ");
            strSql.Append(" where DATEDIFF(S,nodeheartbeattime,getdate()) > @timeOutSenconds");
            DataSet ds = new DataSet();
            DataTable dt = conn.SqlToDataTable(strSql.ToString(), par);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    var model = CreateModel(dr);
                    list.Add(model);
                }
            }
            return list;
        }

        /// <summary>
        /// 得到服务节点数量
        /// </summary>
        public int GetNodeCount(DbConn conn, int serviceId, XXF.BaseService.ServiceCenter.SystemRuntime.EnumRunState runState)
        {
            List<ProcedureParameter> par = new List<ProcedureParameter>();
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select isnull(count(serviceId),0)");
            strSql.Append(" from tb_node ");

            strSql.Append(" where serviceId=@serviceId");
            par.Add(new ProcedureParameter("serviceId", serviceId));

            strSql.Append(" and runstate=@runState");
            par.Add(new ProcedureParameter("runstate", (int)runState));
            var obj = conn.ExecuteScalar(strSql.ToString(), par);
            return Convert.ToInt32(obj);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="search">查询实体</param>
        /// <param name="totalCount">总条数</param>
        /// <returns></returns>
        public IList<tb_node> GetPageList(DbConn conn, tb_node_search search, out int totalCount)
        {
            totalCount = 0;
            List<ProcedureParameter> par = new List<ProcedureParameter>();
            IList<tb_node> list = new List<tb_node>();
            long startIndex = (search.Pno - 1) * search.PageSize + 1;
            long endIndex = startIndex + search.PageSize - 1;
            par.Add(new ProcedureParameter("startIndex", startIndex));
            par.Add(new ProcedureParameter("endIndex", endIndex));

            StringBuilder baseSql = new StringBuilder();
            string sqlWhere = " where 1=1 ";
            baseSql.Append("select row_number() over(order by id desc) as rownum,");
            #region Query
            if (search.serviceid > 0)
            {
                sqlWhere += " and serviceid=@serviceid";
                par.Add(new ProcedureParameter("serviceid", ProcParType.Int32, 4, search.serviceid));
            }
            if (!string.IsNullOrEmpty(search.ip))
            {
                sqlWhere += " and ip like '%'+@ip+'%'";
                par.Add(new ProcedureParameter("ip", ProcParType.NVarchar, 50, search.ip));
            }
            #endregion
            baseSql.Append(" * ");
            baseSql.Append(" FROM tb_node with(nolock)");

            string execSql = "select * from(" + baseSql.ToString() + sqlWhere + ")  as s where rownum between @startIndex and @endIndex";
            string countSql = "select count(1) from tb_node with(nolock)" + sqlWhere;
            object obj = conn.ExecuteScalar(countSql, par);
            if (obj != DBNull.Value && obj != null)
            {
                totalCount = LibConvert.ObjToInt(obj);
            }
            DataTable dt = conn.SqlToDataTable(execSql, par);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    var model = CreateModel(dr);
                    list.Add(model);
                }
            }
            return list;
        }

        #endregion

        #region private
        public tb_node CreateModel(DataRow dr)
        {
            var model = new tb_node();
            if (dr.Table.Columns.Contains("id") && dr["id"].ToString() != "")
            {
                model.id = int.Parse(dr["id"].ToString());
            }
            if (dr.Table.Columns.Contains("servicenamespace") && dr["servicenamespace"].ToString() != "")
            {
                model.servicenamespace = dr["servicenamespace"].ToString();
            }
            if (dr.Table.Columns.Contains("serviceid") && dr["serviceid"].ToString() != "")
            {
                model.serviceid = int.Parse(dr["serviceid"].ToString());
            }
            if (dr.Table.Columns.Contains("sessionid") && dr["sessionid"].ToString() != "")
            {
                model.sessionid = long.Parse(dr["sessionid"].ToString());
            }
            if (dr.Table.Columns.Contains("ip") && dr["ip"].ToString() != "")
            {
                model.ip = dr["ip"].ToString();
            }
            if (dr.Table.Columns.Contains("port") && dr["port"].ToString() != "")
            {
                model.port = int.Parse(dr["port"].ToString());
            }
            if (dr.Table.Columns.Contains("runstate") && dr["runstate"].ToString() != "")
            {
                model.runstate = int.Parse(dr["runstate"].ToString());
            }
            if (dr.Table.Columns.Contains("nodeheartbeattime") && dr["nodeheartbeattime"].ToString() != "")
            {
                model.nodeheartbeattime = DateTime.Parse(dr["nodeheartbeattime"].ToString());
            }
            if (dr.Table.Columns.Contains("boostpercent") && dr["boostpercent"].ToString() != "")
            {
                model.boostpercent = int.Parse(dr["boostpercent"].ToString());
            }
            if (dr.Table.Columns.Contains("errorcount") && dr["errorcount"].ToString() != "")
            {
                model.errorcount = long.Parse(dr["errorcount"].ToString());
            }
            if (dr.Table.Columns.Contains("connectioncount") && dr["connectioncount"].ToString() != "")
            {
                model.connectioncount = long.Parse(dr["connectioncount"].ToString());
            }
            if (dr.Table.Columns.Contains("visitcount") && dr["visitcount"].ToString() != "")
            {
                model.visitcount = long.Parse(dr["visitcount"].ToString());
            }
            if (dr.Table.Columns.Contains("processthreadcount") && dr["processthreadcount"].ToString() != "")
            {
                model.processthreadcount = int.Parse(dr["processthreadcount"].ToString());
            }
            if (dr.Table.Columns.Contains("processcpuper") && dr["processcpuper"].ToString() != "")
            {
                model.processcpuper = decimal.Parse(dr["processcpuper"].ToString());
            }
            if (dr.Table.Columns.Contains("memorysize") && dr["memorysize"].ToString() != "")
            {
                model.memorysize = decimal.Parse(dr["memorysize"].ToString());
            }
            if (dr.Table.Columns.Contains("filesize") && dr["filesize"].ToString() != "")
            {
                model.filesize = decimal.Parse(dr["filesize"].ToString());
            }
            if (dr.Table.Columns.Contains("createtime") && dr["createtime"].ToString() != "")
            {
                model.createtime = DateTime.Parse(dr["createtime"].ToString());
            }
            if (dr.Table.Columns.Contains("interfaceversion") && dr["interfaceversion"].ToString() != "")
            {
                model.interfaceversion = decimal.Parse(dr["interfaceversion"].ToString());
            }
            if (dr.Table.Columns.Contains("protocoljson") && dr["protocoljson"].ToString() != "")
            {
                model.protocoljson = dr["protocoljson"].ToString();
            }

            return model;
        }
        #endregion
    }
}